/*
 * @Description:
 * @Author:Huang Xin Ming
 * @Date:2024-11-07 08:59:58
 * @LastEditors:Huang Xin Ming
 * @LastEditTime:2024-11-11 16:55:50
 */
import { useUserStore } from '@/store/modules/user';
import type { requestOptions } from '@/types/request'
import { useNotify } from '@/components/GlobalNotify/index'

const { showNotify } = useNotify()

// 请求拦截
const requestInterceptor = (options: requestOptions) => {
    // 设置请求超时时间
    options.timeout = __VITE_SERVER_TIMEOUT__
    // 拼接请求地址
    options.url = __VITE_SERVER_BASEURL__ + options.url
    // 设置请求头
    const { Token } = useUserStore()
    console.log('Token',Token);
    options.header = {
        Authorization: `Bearer ${Token}`, // token
        'Content-Type': 'application/json;charset=utf-8',
        ...options.header
    }
    return options
}

export default (options:requestOptions): Promise<any> => {
    showNotify({
        content: '加载中...',
        duration: false,
        icon: 'loading'
    })
    options = requestInterceptor(options)
    return new Promise((resolve,reject) => {
        uni.request({
            ...options,
            success(res:UniApp.RequestSuccessCallbackResult) {
                // 判断返回data是否为object，请求返回值可能不是object
                if(typeof res.data === 'object' && 'code' in res.data) {
                    if(res.data.code === 200) {
                        resolve(res.data)
                        showNotify({
                            content: res.data.msg,
                            duration: 500,
                            type: 'success',
                            icon: 'check-outline'
                        })
                    } else {
                        reject(res.data)
                        showNotify({
                            content: `Error ${res.data.code}:${res.data.msg}`,
                            duration: 2000,
                            type: 'danger',
                            icon: 'close-outline'
                        })
                    }
                } else {
                    resolve(res.data)
                    showNotify({
                        content: '请求成功',
                        duration: 500,
                        type: 'success',
                        icon: 'check-outline'
                    })
                }
            },
            fail(error) {
                reject(error)
                showNotify({
                    content: `Error: ${error.errMsg}`,
                    duration: 2000,
                    type: 'danger',
                    icon: 'close-outline'
                })
            },
            complete() {}
        })
    })
}
